//
//  HMRefreshControl.swift
//  仿一个新浪微博
//
//  Created by 孙家林 on 15/9/24.
//  Copyright © 2015年 sunjialin. All rights reserved.
//

import UIKit

//下拉刷新的偏移量，超出后翻转动画
private let kRefreshPullOffset: CGFloat = -60

//下拉刷新控件,集成在tableView controller上
class HMRefreshControl: UIRefreshControl {
    
    //重写结束刷新方法
    override func endRefreshing() {
        
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    /**
    向下拉表格，y 值越来越小
    向上推表格，y 值越来越大
    从表格顶部向下拉，y值是负数
    拽到一定幅度，会自动进入刷新状态
    */
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    
        
        if frame.origin.y > 0 {
        
            return
        }
        
        //判断是否开始刷新，如果进入刷新状态，播放加载动画
        if refreshing {
        
            refreshView.startLoading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
            print("翻过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
    }

    override init() {
        
        super.init()
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //用KVO监听，最后必须移除
    deinit {
    
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private func setUpUI() {
        
        //KVO 监听frame 属性变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        //隐藏默认的转轮
        tintColor = UIColor.clearColor()
        
        addSubview(refreshView)
        
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    //懒加载控件
    private lazy var refreshView: HMRefreshView = HMRefreshView.refreshView()
}


//下拉刷新 - 负责显示动画
class HMRefreshView: UIView {
    
    //旋转标记
    private var rotateFlag = false {
    
        didSet {
        
            rotateTipIcon()
        }
    }
    
    
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var loadIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    
    private func rotateTipIcon() {
        
        // 在块代码动画中，旋转会就近原则，默认顺时针寻找方向
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        
        UIView.animateWithDuration(1.0) { () -> Void in
            
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    
    }
    
    class func refreshView() -> HMRefreshView {
    
        return NSBundle.mainBundle().loadNibNamed("HMRefreshView", owner: nil, options: nil).last as! HMRefreshView
    }
    
    //开始加载动画
    private func startLoading() {
        
        if loadIcon.layer.animationForKey("loadingAnim") != nil {
        
            return
        }
        //隐藏提示图
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.duration = 1.0
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        
        //开始动画
        loadIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    //停止加载动画
    private func stopLoading() {
    
        tipView.hidden = false
        
        loadIcon.layer.removeAllAnimations()
    }

}